package com.woniu40.petai_user.web;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.woniu40.petai_user.entity.User;
import com.woniu40.petai_user.result.ResponseResult;
import com.woniu40.petai_user.service.ArticleService;
import com.woniu40.petai_user.service.GoodsService;
import com.woniu40.petai_user.service.UserService;
import com.woniu40.petai_user.vo.ArticleVo;
import com.woniu40.petai_user.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    ArticleService articleService;

    @RequestMapping("/login")
    public String login(String userName, String password, Map map,HttpSession session) {
        User user = userService.findUserByName(userName);
        if (user == null) {
            map.put("ErrorResult", "该用户不存在");
            return "login";
        } else {
            if (user.getUserStatus() == 1) {
                if (user.getPassword().equals(password)) {
                    userService.modifyErrorCount0(userName);
                    map.put("ErrorResult", "登录成功");
                    session.setAttribute("user",user);
                    return "redirect:/goods/show";
                } else {
                    int i = user.getErrorCount() + 1;
                    if (i < 5) {
                        map.put("ErrorResult", "密码错误,当前还剩" + (5 - i) + "次机会");
                        userService.modifyErrorCount(userName);
                        return "login";
                    } else {
                        map.put("ErrorResult", "密码错误次数已达上限，账号已被冻结！");
                        userService.modifyStatus(userName);
                        return "login";
                    }
                }
            } else {
                userService.modifyStatus(userName);
                map.put("ErrorResult", "密码输入次数过多，请联系管理员");
                return "login";
            }
        }
    }


    @PostMapping("/reg")
    public String reg(User user, Map map, String checkCode, HttpServletRequest request) {

        //验证验证码
        String vrifyCode = (String) request.getSession().getAttribute("vrifyCode");

        if (vrifyCode == null) {

            map.put("registerResult", "验证码不存在");
            return "register";
        } else {
            if (vrifyCode.toLowerCase().equals(checkCode.toLowerCase())) {
                map.put("registerResult", "验证成功");
                int i = userService.addUser(user);
                if (i == 1) {
                    map.put("registerResult", "注册成功");
                    return "index";
                } else {

                    map.put("registerResult", "注册失败");
                    return "register";
                }
            } else {
                map.put("registerResult", "验证失败");
                return "register";
            }
        }

        //验证密码

        //保存


    }


    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @RequestMapping("/getCode")
    public void defaultKaptcha( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute("vrifyCode", createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    //查询我的关注列表
    @RequestMapping("/myAttention")
    public String myAttention(HttpSession session, Map map) {
        //拿到登陆的用户信息
        User user = (User) session.getAttribute("user");
        int userId = user.getUserId();
        List<User> attentionUsers = userService.findAttentionUsers(userId);
        map.put("attentionUsers", attentionUsers);
        return "center";
    }

    //用户登出
    @RequestMapping("/exit")
    public String exit(HttpSession session){
        session.invalidate();
        return "redirect:/goods/show";
    }
    @RequestMapping("/modifyUser")
    public String modifyUser(@RequestParam(required = false) User user,HttpSession session){
        User user1 = (User) session.getAttribute("user");
        Integer userId = user1.getUserId();
        if (user!=null){
            user.setUserId(userId);
            userService.modifyUser(user);
        }




//        session.setAttribute("user",user);

        return "redirect:/order/list";

    }


   /* @RequestMapping("/modifyUser")
    public String modifyUser(User user){

        userService.modifyUser(user);

        return "index";*/



    //文件上传
    @RequestMapping("/upload")
    public String upload(@RequestParam("myFile") MultipartFile mf,HttpSession session) throws IOException {
        //获取文件名称
        String uploadFileName = mf.getOriginalFilename();
        //获取当前时间
        long timeMillis = System.currentTimeMillis();
        //存到数据库中的文件名称
        String fileName = timeMillis+"_"+uploadFileName;

        //设置文件上传路径
        String path = "D:\\images";

        //创建file对象
        File file = new File(path+File.separator+fileName);

        //将上传的文件上传到配置的路径中
        mf.transferTo(file);

        User user = (User) session.getAttribute("user");
        Integer userId = user.getUserId();
        userService.modifyAvatar(userId,fileName);

        return "redirect:/order/list";
    }

    @RequestMapping("/modifyAvatar")
    public String upload1(@RequestParam(value = "myAvatar",required = false) MultipartFile mf,HttpSession session) throws IOException {
        System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!");
        //获取文件名称
        String uploadFileName = mf.getOriginalFilename();
        //获取当前时间
        long timeMillis = System.currentTimeMillis();
        //存到数据库中的文件名称
        String fileName = timeMillis+"_"+uploadFileName;

        //设置文件上传路径
        String path = "D:\\images\\user";

        //创建file对象
        File file = new File(path+File.separator+fileName);

        //将上传的文件上传到配置的路径中
        mf.transferTo(file);

        User user = (User) session.getAttribute("user");
        Integer userId = user.getUserId();
        userService.modifyAvatar(userId,fileName);

        return "redirect:/order/list";
    }


    @RequestMapping("/")
    public String goHome(){
        return "redirect:goods/show";
    }

}